<template>
	<view class="body chat" @tap="closeMask">
		<view class="com">
			<scroll-view class="scrollView" scroll-y scroll-anchoring show-scrollbar scroll-with-animation
				:scroll-into-view="scrollViewId">
				<view class="scroll-content">
					<view v-for="(item, idx) in messagesList" :key="idx">
						<view v-if="item.Grade == 1" class="msgItem" :class="getSender(item) ? 'right' : 'left'">
							<up-avatar mode="aspectFill" :src="getPicture(item)" size="45"></up-avatar>
							<view>
								<view class="nick_name" v-if="item.Type == 2 && item.myUserId != item.Sender.user_id">
									{{ item.Sender.nick_name }}
								</view>
								<view class="content">
									<messageContent :index="idx" :item="item" :messagesList="messagesList"
										:messageType="1" @longpress="longpressFn(item)" @playVideoFn="playVideoFn"
										@receiveRedEnvelopeFn="receiveRedEnvelopeFn"
										@handleCallFn="(call_type: number) => { handleCall(call_type, chatnfo,1) }" />
									<view class="quote" v-if="item.quote">
										<view>
											<view class="quoteName">{{ item.nick_name }}：</view>
											<messageContent :item="item.quote" :messageType="2" />
										</view>
									</view>
								</view>
							</view>
						</view>
						<view v-if="item.Grade == 2" class="timestamp">
							{{ item.Content.Text }}
						</view>
						<view v-if="shouldShowTime(idx, messagesList)" class="timestamp">
							{{ formattingTime(item.Time, 2) }}
						</view>
					</view>
				</view>
				<view id="bottom"></view>
			</scroll-view>

			<!-- 视频 -->
			<playVideo ref="playVideoRef" />
			<!-- 红包 -->
			<receiveRedEnvelope ref="receiveRedEnvelopeRef" @redDetailsFn="redDetailsFn" />

			<!-- 长按 -->
			<longPressPop ref="longPressPopRef" @longPressPopFn="longPressPopFn" />



		</view>
		<chatInput v-show="isDetermineYouGroup" ref="chatInputRef" :chatnfo="chatnfo" :myUserInfo="myUserInfo"
			:isGroupChat="isGroupChat" :baseDataType="baseDataType" :chatId="chatId" @sendChatFn="(e: any) => {
        messagesList.unshift(e);
        initScrollBar();
      }
        " />
		<view v-show="!isDetermineYouGroup" class="determineYouGroup">不可操作</view>
	</view>
</template>

<script setup lang="ts">
	import {
		ref,
		nextTick,
		getCurrentInstance,
		watch,
		computed,
		onMounted,
		onBeforeUnmount,
	} from "vue";
	import { onLoad, onNavigationBarButtonTap, onShow } from "@dcloudio/uni-app";
	import chatInput from "./components/chatInput.vue";
	import messageContent from "./components/messageContent.vue";
	import playVideo from "./components/playVideo.vue";
	import longPressPop from "./components/longPressPop.vue";
	import receiveRedEnvelope from "./components/receiveRedEnvelope.vue";

	import {
		determineFriendUpdate,
		MessageReadReceipt,
		HistoryMessage,
		GroupInfo,
		RedEnvelopeInFo,
		UnreadMessage,
	} from "@/api/ImApi";
	import { useStore } from "@/stores";
import { number } from "echarts";

	// 获取当前实例和 store
	const instance = getCurrentInstance()?.appContext.config.globalProperties;
	const store = useStore();
	// 当前界面是单聊还是群聊
	const isGroupChat = ref<boolean>(false);
	const baseDataType = ref<string>();

	// 用户和聊天信息
	let chatnfo = ref();
	let myUserInfo = ref();
	let chatId = ref();
	let chatInputRef = ref();

	onLoad((options : any) => {
		console.log(options)
		isGroupChat.value = options.Type == 1 ? false : true;
		baseDataType.value = isGroupChat.value ? "groupChat" : "singleChat";
		chatId.value = isGroupChat.value ? options.group_id : String(options.user_id);
		console.log(chatId.value, ' chatId.value chatId.value')
		if (isGroupChat.value) {
			getGroupInfo();
		}
		initFn();
	});
	onShow(() => {
		if (uni.getStorageSync("submitSendRed")) {
			uni.removeStorageSync("submitSendRed");
			initFn();
		}

		// 群聊
		if (isGroupChat.value) {
			getGroupInfo();
		}
	});
	// 判断是否在群里
	let isDetermineYouGroup = ref<boolean>(true);
	// 获取群的信息
	const getGroupInfo = () => {


		GroupInfo({
			group_id: chatId.value,
		})
			.then((e : any) => {
				isDetermineYouGroup.value = true;
				let obj = { ...chatnfo.value, ...e };
				chatnfo.value = obj;
				initFn();
			})
			.catch(() => {
				isDetermineYouGroup.value = false;
			});
	};

	// 初始化数据
	const initFn = async () => {
		myUserInfo.value = uni.getStorageSync("userInfo");
		page.value = 1;
		// 设置单聊标题
		if (!isGroupChat.value) {
			let chatList = await instance?.$db.loadData("chatList", {
				id: Number(chatId.value),
			});
			console.log(22)
			let friendList = await instance?.$db.loadData("friendList", {
				id: Number(chatId.value),


			});
			console.log(friendList, 111)
			chatnfo.value = {
				...friendList[0],
				...chatList[0],
			};

			uni.setNavigationBarTitle({
				title: chatnfo.value.notes || chatnfo.value.nick_name,
			});

			determineFriendUpdate(chatnfo.value).then((e) => {
				chatnfo.value = { ...chatnfo.value, ...e };
			});
		}
		// 设置群聊标题
		if (isGroupChat.value) {
			let chatList = await instance?.$db.loadData("chatList", {
				id: chatId.value,
			});
			chatnfo.value = chatList[0];
			let title = chatnfo.value.group_name;
			if (title.length > 10) {
				title = title.substring(0, 10) + "...";
			}
			uni.setNavigationBarTitle({
				title: title + "（" + chatnfo.value.member.length + "）",
			});
		}

		getSingleChat();
		UnreadMessage();
	};


	const longPressPopRef = ref<any>(null);
	// 长按内容
	const longpressFn = (item : any) => {

		longPressPopRef.value?.openShow(item);

	};
	// 引用或者删除
	const longPressPopFn = (item : any) => {
		if (item.longPressPopType == 1) {
			chatInputRef.value?.replyFn(item);

		}
		else if (item.longPressPopType == 2) {

		}

	}

	// 播放视频
	const playVideoRef = ref<any>(null);
	const playVideoFn = (item : any) => {
		playVideoRef.value?.playVideoFn(item);
	};

	// 点击红包
	const receiveRedEnvelopeRef = ref<any>(null);
	const receiveRedEnvelopeFn = async (item : any) => {
		console.log(item)
		// 判断是否是单聊自己发的红包
		if (!isGroupChat.value && getSender(item)) {
			redDetailsFn(item);

			return;
		}
		let res = await RedEnvelopeInFo(item);
		const redMsg = await instance?.$db.loadData(baseDataType.value, {
			MessageId: item.MessageId,
			chatId: chatId.value,
			page: 1,
			limit: 1,
			Cmd: 6

		});

		console.log(redMsg)

		if (res) {
			let headName = {
				picture: getPicture(item),
				nick_name: getNickName(item),
			};
			receiveRedEnvelopeRef.value?.receiveRedEnvelopeFn({
				...item,
				...res,
				...headName,
			});
		}
	};

	// 关闭红包弹窗
	const closeRedMask = () => {
		receiveRedEnvelopeRef.value?.closeMask();
	};
	// 查看红包详情
	const redDetailsFn = (item : any) => {
		let headName = {
			picture: getPicture(item),
			nick_name: getNickName(item),
		};
		let parameter =
			"?picture=" +
			"&data=" +
			encodeURIComponent(
				JSON.stringify({
					item,
					headName,
				})
			);
		closeRedMask();
		console.log(item, '-------item')
		instance?.goTo("/pages/red/redDetails" + parameter);
	};

	// 聊天消息列表和分页
	let messagesList = ref<Array<any>>([]);
	let max_MessageId = ref<number>(0);
	let page = ref<number>(1);
	let limit = ref<number>(20);
	// 判断是否继续请求历史消息
	let isGetsetUnread = ref<boolean>(true);
	// 锁标识，避免多次请求
	let isRequesting = ref<boolean>(false);

	// 加载更多数据
	const loadMoreData = () => {
		if (!isRequesting.value) {
			page.value++;
			getSingleChat();
		}
	};

	// 获取聊天记录
	const getSingleChat = async () => {
		if (isRequesting.value) return; // 防止重复请求
		isRequesting.value = true;
		console.log(baseDataType.value);
		console.log(chatId.value);
		const messages = await instance?.$db.loadData(baseDataType.value, {
			chatId: chatId.value,
			page: page.value,
			limit: limit.value,
		});
		console.log(messages);
		if (page.value == 1) {
			messagesList.value = messages;
			// 有数据开启观察
			if (messages.length) {
				if (messages.length >= limit.value) {
					observeLoadMore();
				}
				//最后一条数据跟后端返回的对比
				const lastMessage = await instance?.$db.loadData(baseDataType.value, {
					chatId: chatId.value,
					page: 1,
					limit: 1,
					Grade: 1,
					Cmd: { $ne: 7 },
				});
				console.log("最后一条数据跟后端返回的对比-", lastMessage);
				let lastMessageId = lastMessage[0]?.MessageId || 0;
				let newMessageId = chatnfo.value.MessageId;
				// 如果最后一条数据小于后端返回的数据，那么sort=2
				console.log("最后一条数据跟后端返回的对比-", lastMessageId, newMessageId);
				console.log("max_MessageId-", max_MessageId.value);

				if (lastMessageId < newMessageId || lastMessageId < max_MessageId.value) {
					setUnread(2);
				} else {
					// 否者直接设置已读
					updateDataFn();
				}
				// 如果本地数据不满足limit条数据，并且第一条数据还不为1的话那么sort=1
				if (
					messages.length < limit.value &&
					messages[messages.length - 1].MessageId != 1
				) {
					setUnread(1);
				}
			} else {
				setUnread(2);
			}
		} else {
			if (messages.length) {
				messagesList.value = [...messagesList.value, ...messages];
			} else {
				if (isGetsetUnread.value) {
					setUnread(1);
				}
			}
		}
		console.log("聊天记录", page.value, messagesList.value);

		isRequesting.value = false; // 请求结束后解锁
	};

	// 设置未读消息
	const setUnread = async (type : any = "") => {
		let sort = type;

		if (isGetsetUnread.value) {
			// 请求历史消息

			const res = await fetchHistoryMessages(sort);
			const HistoryMessageList = res.list
			max_MessageId.value = res.max_MessageId
			if (HistoryMessageList.length === 0 || HistoryMessageList.length < 100) {
				isGetsetUnread.value = false; // 没有更多数据，不再请求
				updateDataFn();
			}
			// 设置某个聊天已读
			const contentList = HistoryMessageList.map((e : any) => ({
				...e.Content,
				myUserId: myUserInfo.value.user_id,
				chatId: chatId.value,
				unread: 0,
				id: chatId.value + "_" + e.Content.MessageId,
			}));

			console.log("接口的数据", contentList);

			if (contentList.length > 0) {
				// 保存新消息到数据库
				await instance?.$db.saveData(baseDataType.value, contentList);
				// 重新加载数据
				page.value = 1;
				getSingleChat();
			} else {
				// 消息已读回执
				let key = isGroupChat.value ? chatId.value : chatnfo.value.SessionId;
				await MessageReadReceipt({
					key,
				});
			}
		}
		await instance?.$db.updateData(
			baseDataType.value,
			{ chatId: chatId.value, unread: 1 },
			{ unread: 0 }
		);

		// 保存聊天项到聊天列表
		if (messagesList.value[0]) {
			const chatItem = {
				...messagesList.value[0],
				...chatnfo.value,
				Time:messagesList.value[0].Time,
				id: isGroupChat.value ? chatId.value : Number(chatId.value),
			};
			const chatItemCopy = instance?.deepClone(chatItem);
			console.log('chatItemCopy',chatItemCopy)
			await instance?.$db.saveData("chatList", [chatItemCopy]);
		}
	};
	// 消息已读回执
	const updateDataFn = async () => {
		let key = isGroupChat.value ? chatId.value : chatnfo.value.SessionId;
		if (key) {
			MessageReadReceipt({
				key,
			});
			// 更新数据库中的未读消息状态
			instance?.$db.updateData(
				baseDataType.value,
				{ chatId: chatId.value, unread: 1 },
				{ unread: 0 }
			);
			console.log(chatId.value)
			await store.db.deleteData("unreadMessage", { id: Number(chatId.value )});
			instance?.getUnreadCount();


		}
	};

	// 请求历史消息的封装
	const fetchHistoryMessages = async (sort : number) => {
		let obj : any = {
			time:
				sort === 2
					? messagesList.value[0]?.Time
					: messagesList.value[messagesList.value.length - 1]?.Time,
			sort,
		};
		if (isGroupChat.value) {
			obj["groupId"] = chatId.value;
		} else {
			obj["sessionId"] = chatnfo.value.SessionId;
		}
		const historyMessages = await HistoryMessage(obj);
		return historyMessages;
	};

	// 最新消息监听
	const latestData = computed(() => store.latestData);
	watch(latestData, async (newValue : any) => {
		if (newValue.Cmd != 7) {
			// 单聊
			if (newValue.Type == 1 && newValue.Sender == chatnfo.value.user_id) {
				if (newValue.Grade == 1) {
					if (newValue.MessageId) {
						newValue.id = chatId.value + "_" + newValue.MessageId
						delete newValue.Id
					}
					console.log(newValue)
					messagesList.value.unshift(newValue);
					updateDataFn();
				}
			}
			// 群聊
			if (newValue.Type == 2 && newValue.chatId == chatId.value) {
				if (newValue.Grade == 1) {
					if (newValue.MessageId) {
						newValue.id = chatId.value + "_" + newValue.MessageId
						delete newValue.Id
					}
					messagesList.value.unshift(newValue);
					updateDataFn();
				}
				// 通知消息
				if (newValue.Grade == 2) {
					// 有文案进来 添加到界面
					console.log(newValue.Content.Text);
					if (newValue.Content.Text) {
						messagesList.value.unshift(newValue);
						updateDataFn();
					} else {
						// 更新了群资料
						getGroupInfo();
					}
				}
			}
		}
	});

	// 关闭输入框弹窗
	const closeMask = () => {
		chatInputRef.value?.closeMask();
	};

	// 滚动条初始化
	let scrollViewId = ref<string>("");
	const initScrollBar = () => {
		nextTick(() => {
			scrollViewId.value = "";
			setTimeout(() => {
				scrollViewId.value = "bottom";
			}, 50);
		});
	};

	let observer : any = null;

	// 观察器方法
	const observeLoadMore = () => {
		if (observer) {
			observer.disconnect();
		}

		observer = uni.createIntersectionObserver(null);
		observer.relativeToViewport().observe("#bottom", (res : any) => {
			if (res.intersectionRatio > 0) {
				loadMoreData();
			}
		});
	};
	// 整理Sender
	const getSender = (item : any) => {
		return (

			item.myUserId == (isGroupChat.value ? item.Sender.user_id : item.Sender)
		);
	};
	const getPicture = (item : any) => {
		let boo = getSender(item);
		return boo
			? myUserInfo.value.picture
			: isGroupChat.value
				? item.Sender.picture
				: chatnfo.value.picture;
	};
	const getNickName = (item : any) => {
		let boo = getSender(item);
		return boo
			? myUserInfo.value.nick_name
			: isGroupChat.value
				? item.Sender.nick_name
				: chatnfo.value.nick_name;
	};

	// 生命周期
	onNavigationBarButtonTap(() => {
		if (isGroupChat.value) {
			instance?.goTo("/pages/group/groupSettings?chatId=" + chatId.value);
		} else {
			instance?.goTo("/pages/chat/friendDetails?chatId=" + chatId.value);
		}
	});
	onMounted(() => { });
	onBeforeUnmount(() => {
		if (observer) {
			observer.disconnect();
		}
	});
</script>

<style scoped lang="scss">
	@import "../../static/scss/chat.scss";
</style>